# coding= utf-8

import requests
import json
import sys
import codecs
import warnings
import pymongo
import time

sys.stdout = codecs.getwriter('utf-8')(sys.stdout.detach())
warnings.filterwarnings("ignore")


class Move:
    def __init__(self):
        self.month = sys.argv[1]
        # self.month = '2024-07'

        # 连接MongoDB
        self.myclient = pymongo.MongoClient("mongodb://localhost:27017/")
        mydb = self.myclient["xp_analyse"]
        self.my_task = mydb["wt_task"]
        self.low_order = mydb["wt_low_order"]

    def move_to_system(self):
        # 更新状态同步中
        self.my_task.update({"month": self.month}, {"$set": {"sync_asin_system": "pending"}})

        orders = self.low_order.find({"is_human": 1, "has_moved": {"$exists": False}, "month": self.month})
        post_data = []
        ids = []

        for i in orders:
            item = {
                'asin': i.get('asin'),
                'group_name': i.get('group_name'),
                'country_desc': i.get('country_desc'),
                'limit_type': i.get('limit_type'),
                'limit_reason': i.get('limit_reason'),
            }
            post_data.append(item)
            ids.append(i.get('_id'))

            # 满一千提交一次同步
            if len(post_data) >= 1000:
                print('等待1s')
                time.sleep(1)
                self.post_to_system(post_data, ids)
                post_data = []
                ids = []

        # 最后不满1000，单独提交一次
        if len(post_data) > 0:
            print('不满1000，最后提交！' + str(len(post_data)))
            self.post_to_system(post_data, ids)

        # 更新状态同步完成
        print('同步完毕！')
        self.my_task.update({"month": self.month}, {"$set": {"sync_asin_system": "completed"}})
        self.myclient.close()

    def post_to_system(self, limit_data, ids):
        # url = "http://local-sys.com/common/analyse/insert_limit_asin"
        url = "https://wangting.wszzl.cn/common/analyse/insert_limit_asin"
        json_data = {
            'asins': json.dumps(limit_data),
        }
        response = requests.post(url, data=json_data)

        # 检查请求是否成功
        if response.status_code == 200:
            data = response.json()
            print(data)

            # 更新asin状态为已同步
            res = self.low_order.update_many({"_id": {"$in": ids}}, {"$set": {"has_moved": 1}})
            print("更新asin同步状态：" + str(res.acknowledged))
        else:
            print("请求失败，状态码：", response.status_code)
            print(response.text)


move = Move()
move.move_to_system()
